<?php
class App_Tpl_List extends Mozg_Templator
{
	protected $_showCells = array('title', 'icons');
	protected $_emptyListMessage = 'EMPTY_LIST';
	protected $_paginatorTpl = 'Paginator';
	protected $_showEmptyList = false;
	protected $_cellClasses = array();
	protected $_sortable = false;
	
	protected $_page = 1;
	protected $_pages = '';
	protected $_objects = array();
	protected $_headers = array();
	protected $_showHeader = false;
	protected $_cellCount = 0;
	
	protected function CreateList(array $objects = array(), Mozg_Paginator $paginator = null, $pattern = '')
	{
		$this->_objects = $objects;
		
		if ($paginator)
		{
	        $this->_page = $paginator->GetPage();
	        $this->_pages = $this->GetTpl($this->_paginatorTpl)->Get($paginator, $pattern);
		}

		if (sizeof($objects) || $this->_showEmptyList)
		{
			$this->PrepareCellList();
			return $this->RenderList();
		}
		else
		{
			return $this->RenderEmptyList();
		}
	}
	
	protected function PrepareCellList()
	{
		if ($this->_sortable)
		{
			array_unshift($this->_showCells, 'sortable');
		}
		
		$this->_showCells = array_unique($this->_showCells);
		
		$cells = array();
		foreach ($this->_showCells as $cellName)
		{
			if (method_exists($this, 'GetCell' .$cellName))
			{
				$cells[] = $cellName;
			}
			
			if (method_exists($this, 'GetHeader' .$cellName))
			{
				$this->_headers[$cellName] = $this->{'GetHeader' .$cellName}();
				$this->_showHeader = true;
			}
			else
			{
				$this->_headers[$cellName] = false;
			}
		}
		
		$this->_showCells = $cells;
		$this->_cellCount = sizeof($cells);
	}
	
	protected function GetCellSortable()
	{
        $icons['sortable'] = array('title' => 'SORT');
		return $this->GetTpl('Icon')->GetIconSet($icons, 'list');
	}
	
	protected function GetRow($obj)
	{
		$this->obj = $obj;
		return $this->render('list/_row.phtml');
	}
	
    protected function RenderList()
    {
    	if ($this->_sortable)
    	{
    		Mozg::SubAction()->Add('RequiredJS', array($this, 'SortableJS'), array(), 'SortableList');
    	}
    		
    	return $this->render('list/_list.phtml');
    }
    
    public function SortableJs()
    {
    	return $this->render('list/js/_sortable.js');
    }
    
    protected function RenderEmptyList()
    {
    	return $this->render('list/_emptylist.phtml');
    }
	
    protected function GetSortableValue($obj)
    {
    	return $obj->GetId();
    }
    
	protected function GetCellTitle($obj)
	{
		return $obj->GetTitle();
	}
	
	protected function GetCellIcons($obj)
	{
		return '';
	}
}